package okl.lab.namesFilter.service
{
	import flash.net.registerClassAlias;
	
	import mx.collections.ArrayCollection;
	import mx.collections.IList;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import okl.lab.namesFilter.model.AppModel;
	import okl.lab.namesFilter.model.vo.User;
	import okl.lab.namesFilter.service.utils.ServiceUtils;
	
	import org.robotlegs.mvcs.Actor;
	
	/**
	 * 	Loads, parse users data xml and notify model.
	 * Parse responsibility can be decoupled and injected.
	 * 
	 *	@author "oleksandr.kulinchenko@gmail.com"
	 */
	public class HttpUsersService extends Actor implements IUsersService
	{
		[Inject]public var model:AppModel;
		
		private var _service:HTTPService;
		public function HttpUsersService()
		{
			super();
			init();
		}
		
		private function init():void{
			_service=new HTTPService();	
			_service.addEventListener(ResultEvent.RESULT, result);
			_service.addEventListener(FaultEvent.FAULT, ServiceUtils.faultHandler);
			_service.resultFormat=HTTPService.RESULT_FORMAT_E4X
		}
		
		public function getUsers():void
		{
			_service.url = model.settings.usersXmlUrl;
			_service.send();
		}
		
		private function result(event:ResultEvent):void{
			model.users = parseE4X(event.result as XML);
			
		
		}
		
		private function parseE4X(list:XML):ArrayCollection{
			var xmlUsers:XMLList = list..user;
			var result:ArrayCollection = new ArrayCollection();
			for each(var xmlUser:XML in xmlUsers){
				var user:User = new User();
				user.firstName=xmlUser.firstName;
				user.lastName=xmlUser.lastName;
				user.female=(xmlUser.@female.toString().toLowerCase()=="true");
				
				result.addItem(user);
			}
			return result;
		}
	}
}